import json
import os

from django.core.exceptions import ValidationError
from django.shortcuts import render, redirect
from django.contrib.auth import authenticate, login, logout
from django.contrib import messages
from django.urls import reverse
from django.views.decorators.csrf import csrf_exempt

from PM.models import User, UserModelForm  # 导入自定义的User模型和UserModelForm

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

# 读取 config.json 文件获取部门信息
config_path = os.path.join(BASE_DIR, 'config.json')
with open(config_path, 'r') as config_file:
    config = json.load(config_file)
    DEPARTMENTS = [(dept, dept) for dept in config.get('DEPARTMENTS', [])]


def register(request):
    if request.method == 'POST':
        form = UserModelForm(request.POST)
        if form.is_valid():
            user = form.save(commit=False)
            user.set_password(form.cleaned_data['password'])
            user.role = 'user'  # 确保 role 字段被设置为 'user'
            user.save()
            messages.success(request, 'Account created successfully')
            return redirect('login')
        else:
            messages.error(request, 'Please correct the error below.')
    else:
        form = UserModelForm()
    return render(request, 'register.html', {'form': form})


@csrf_exempt
def user_login(request):
    if request.method == 'POST':
        email = request.POST['email']
        password = request.POST['password']
        try:
            user = User.objects.get(email=email)
            if user.check_password(password):
                login(request, user)
                # 将用户所有信息写入session
                request.session['user_id'] = user.id
                request.session['username'] = user.username
                request.session['email'] = user.email
                request.session['engineer_id'] = user.engineer_id
                request.session['department'] = user.department
                request.session['role'] = user.role
                return redirect('index')  # 登录成功后跳转到index页面
            else:
                messages.error(request, 'Invalid email or password')
        except User.DoesNotExist:
            messages.error(request, 'Invalid email or password')
        return redirect('login')
    return render(request, 'login.html', {'register_url': reverse('register')})  # 添加register_url到上下文


def user_logout(request):
    request.session.flush()  # 使用flush()来完全删除session
    return redirect('login')


def user_management(request):
    if request.method == 'POST':
        action = request.POST.get('action')
        if action == 'add':
            form = UserModelForm(request.POST)
            if form.is_valid():
                user = form.save(commit=False)
                # 添加密码设置逻辑
                user.save()
                messages.success(request, '用户添加成功')
            else:
                messages.error(request, '请更正以下错误')
        elif action == 'edit':
            user_id = request.POST.get('user_id')
            try:
                user = User.objects.get(id=user_id)
                # 修改为使用request.POST数据直接更新，而不是使用ModelForm
                user.email = request.POST.get('email')
                user.name = request.POST.get('name')
                user.department = request.POST.get('department')
                user.role = request.POST.get('role')
                user.engineer_id = request.POST.get('engineer_id')
                # 检查密码字段是否为空，不为空才更新密码
                password = request.POST.get('password')
                if password:
                    user.set_password(password)
                user.save()
                messages.success(request, '用户信息更新成功')
            except User.DoesNotExist:
                messages.error(request, '用户不存在')
            except Exception as e:
                messages.error(request, f'更新失败: {str(e)}')
        elif action == 'delete':
            user_id = request.POST.get('user_id')
            user = User.objects.get(id=user_id)
            user.delete()
            messages.success(request, '用户删除成功')
        return redirect('user_management')

    users = User.objects.all()
    form = UserModelForm()
    return render(request, 'user_management.html',
                  {'users': users, 'form': form, 'departments': DEPARTMENTS, 'current_user': request.current_user})


def account_info(request):
    if request.method == 'POST':
        # 处理上传的签名图片
        signature_image = request.FILES.get('signature_image')
        if signature_image:
            # 确保签名文件夹存在
            signature_folder = os.path.join(BASE_DIR, 'static', 'signature')
            os.makedirs(signature_folder, exist_ok=True)

            # 保存签名图片，文件名为工程师ID
            signature_path = os.path.join(signature_folder, f"{request.current_user['engineer_id']}.png")
            with open(signature_path, 'wb+') as destination:
                for chunk in signature_image.chunks():
                    destination.write(chunk)
            messages.success(request, '签名图片上传成功！')
        else:
            messages.error(request, '请选择签名图片！')
        return redirect('account_info')

    # 获取当前用户信息
    current_user = request.current_user
    user_info = {
        'username': current_user['username'],
        'email': current_user['email'],
        'engineer_id': current_user['engineer_id'],
        'department': current_user['department']
    }

    return render(request, 'account_info.html', {'user_info': user_info, 'current_user': request.current_user})
